#include "serial.h"
#include<QDataStream>


#ifdef IS_INSTANCE
Serial* Serial::mPtr = nullptr;
Serial *Serial::instance()
{
    if(nullptr == mPtr)
        mPtr = new Serial();
    return mPtr;
}
#endif

Serial::Serial(QObject *parent) : QObject(parent)
{
    serial = new QSerialPort;
    connect(serial, &QSerialPort::readyRead, this, [=]()
    {
        QByteArray data = serial->readAll();
        emit haveReceive(data);
    });
}

QStringList Serial::findPort()
{
    QStringList portBuff;
    foreach (const QSerialPortInfo &info,QSerialPortInfo::availablePorts())
    {
        QSerialPort serial;
        serial.setPort(info);
        if(serial.open(QIODevice::ReadWrite))
        {
            portBuff.append(serial.portName());
            serial.close();
        }
    }
    return portBuff;
}

bool Serial::open(QString port,quint64 baud)
{
    if(serial->isOpen())    serial->close();
    serial->setPortName(port);
    if(!serial->open(QIODevice::ReadWrite))
        return false;
    switch (baud)
    {
        case 1200: serial->setBaudRate(QSerialPort::Baud1200);   break;
        case 4800: serial->setBaudRate(QSerialPort::Baud4800);   break;
        case 9600: serial->setBaudRate(QSerialPort::Baud9600);   break;
        case 19200: serial->setBaudRate(QSerialPort::Baud19200);  break;
        case 38400: serial->setBaudRate(QSerialPort::Baud38400);  break;
        case 57600: serial->setBaudRate(QSerialPort::Baud57600);  break;
        case 115200: serial->setBaudRate(QSerialPort::Baud115200); break;
    }
    switch (8){
        case 5:     serial->setDataBits(QSerialPort::Data5);     break;
        case 6:     serial->setDataBits(QSerialPort::Data6);     break;
        case 7:     serial->setDataBits(QSerialPort::Data7);     break;
        case 8:     serial->setDataBits(QSerialPort::Data8);     break;
        default:     break;
    }
    switch (0){
        case 0:     serial->setParity(QSerialPort::NoParity);   break;
        default:    break;
    }
    switch (1){
        case 1: serial->setStopBits(QSerialPort::OneStop);  break;
        case 2: serial->setStopBits(QSerialPort::TwoStop);  break;
        default:     break;
    }
    serial->setFlowControl(QSerialPort::NoFlowControl);
    return true;
}

qint64 Serial::sendData(QByteArray data)
{
    bool isOk = 0;
    if(serial->write(data) > 0)
        isOk = 1;
    return isOk;
}

qint64 Serial::sendData(QString data)
{
    bool isOk = 0;
    if(serial->write(data.toLatin1()) > 0)
        isOk = 1;
    return isOk;
}

